from rest_framework import serializers
from backend.models import Menu
from user.models import User
from school.models import Position, Role, School
from school.serializers import SchoolSerializer
from .models import BackendLog


class UserLogSerializerField(serializers.Field):
    # 自定义字段
    def to_representation(self, value):
        # to_representation：序列化时返回的数据
        if value == "AnonymousUser":
            return {"id": None, "username": "匿名用户"}

        try:
            user = User.objects.get(pk=value)
            return {"id": user.id, "username": user.username}
        except User.DoesNotExist:
            return {"id": None, "username": "未知用户"}

    def to_internal_value(self, data):
        if isinstance(data, dict):
            return data.get('id', '匿名用户')
        return data


class LogSerializer(serializers.ModelSerializer):
    user = UserLogSerializerField()

    class Meta:
        model = BackendLog
        fields = '__all__'


class PositionItemSerializer(serializers.ModelSerializer):
    menus = serializers.SerializerMethodField()
    school = SchoolSerializer(read_only=True)  # 只读字段，用于序列化时显示详细数据
    school_id = serializers.PrimaryKeyRelatedField(
        queryset=School.objects.all(),
        source='school',  # 将此字段与 `school` 关联，以便反序列化时使用
        # write_only=True  # 只写字段，用于反序列化时接收主键
    )

    class Meta:
        model = Position
        fields = '__all__'
        depth = 1

    def get_menus(self, obj):
        if obj.get_children():
            return PositionItemSerializer(obj.get_children(), many=True).data
        return None


class MenuItemSerializer(serializers.ModelSerializer):
    menus = serializers.SerializerMethodField()
    parent = serializers.PrimaryKeyRelatedField(queryset=Menu.objects.all(), required=False)

    class Meta:
        model = Menu
        fields = ['id', 'permission', 'type', 'title', 'name', 'component', 'icon', 'path', 'is_frame', 'parent',
                  'menus']
        # fields = '__all__'
        depth = 1

    def get_menus(self, obj):
        if obj.get_children():
            return MenuItemSerializer(obj.get_children(), many=True).data
        return None


class RoleSerializer(serializers.ModelSerializer):
    name = serializers.CharField(allow_null=True, required=False)
    # position = serializers.PrimaryKeyRelatedField(queryset=Position.objects.all(), required=False)
    menu = MenuItemSerializer(read_only=True, many=True)  # 只读字段，用于序列化时显示详细数据
    menu_list = serializers.PrimaryKeyRelatedField(
        queryset=Menu.objects.all(),
        many=True,
        source='menu',  # 将此字段与 `Menu` 关联，以便反序列化时使用
        required=False
    )
    position = serializers.PrimaryKeyRelatedField(queryset=Position.objects.all(), required=False)
    position_obj = PositionItemSerializer(source='position',read_only=True)

    class Meta:
        model = Role
        fields = '__all__'
        depth = 1
